<template>
  <div>
    <!-- <div class="pages-wrp">
    <div class="add-page" @click="addPage">添加商品介绍</div>
    <div class="pages">
      <div v-for="(page,index) in pages" :key="page.id" :class="{page: 1, selected: index===curIndex }" @click="selectPage(page,index)">
        {{ page.name || page.id }}
         <span v-show="index!==curIndex" @click="removePage(page.id,index)" class="page-close">&Cross;</span>
      </div>
    </div>
  </div> -->
    <!-- <input type="file" accept="image/*" @change="testImport"/> -->
    <el-row
      class="editorOutline"
      style="border: 1px solid rgb(15, 22, 66); border-radius: 10px"
    >
      <el-col class="blocks" style="height: 100vh" :span="3">
        <div id="blocks"></div>
      </el-col>
      <el-col class="gjs" :span="21">
        <div id="gjs"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import { initializeGrapesJS } from "../services/grapesjsService";
export default {
  name: "InitEditor",
  data: () => ({
    editor: null,
    pm: null,
    curIndex: 0,
    pages: [
      {
        id: "page-1",
        name: "Page 1",
        click: false,
        component: '<div id="comp1">Page 1</div>',
        styles: "#comp1 { color: red }",
      },
    ],
  }),

  mounted() {
    let that = this;
    let { editor } = initializeGrapesJS("gjs", "blocks", this.pages);
    that.editor = editor;
    // that.editor = editor;
    that.pm = editor.Pages;
    that.fullscreen(editor);
    that.preview(editor);
  },

  methods: {
    // 传入html代码进行渲染
    importByHTMLText(html) {
      this.editor.setComponents(html);
    },

    // 使用远端路径进行渲染——.html文件
    importByHTMLPath(path) {
      let that = this;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", path, true);
      xhr.setRequestHeader("Accept", "text/html");
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          // 处理接收到的HTML数据
          that.editor.setComponents(xhr.responseText || "");
        }
      };
      xhr.send();
    },

    // 修改文件上传监听配置
    setUploadConfig(methods) {
      let assetManager = this.editor.AssetManager;
      assetManager.config.multiUpload = false;
      // 设置上传函数
      assetManager.config.uploadFile = async (e) => {
        let files = [];
        // 拖拽图片上传
        if (e.type == "drop") {
          files = [].slice.call(e.dataTransfer.files); // es5 格式
        } else {
          files = e.target.files;
        }
        const file = files[0];
        if (!file) return;
        // 判断文件类型
        if (!file.type.startsWith("image")) {
          alert("文件格式错误！");
          return;
        }
        try {
          console.log("正在上传");
          const url = await methods(file);
          assetManager.add(url);
          console.log("上传成功");
        } catch (err) {
          console.error("上传失败", err);
        }
      };
    },

    setVideoUploadCommands(methods) {
      this.editor.Commands.add("setVideoUploadCommands", {
        run(editor, sender) {
          // 创建文件输入元素
          const fileInput = document.createElement("input");
          fileInput.type = "file";
          fileInput.accept = "video/*";
          fileInput.onchange = async () => {
            const file = fileInput.files[0];
            if (file) {
              // 检查文件类型
              const validVideoTypes = ["video/mp4", "video/webm", "video/ogg"];
              if (!validVideoTypes.includes(file.type)) {
                alert("只能上传视频文件");
                return;
              }
              try {
                console.log("正在上传");
                const url = await methods(file);
                editor.getSelected().addAttributes({ src: url });
                console.log("上传成功");
              } catch (err) {
                console.error("上传失败", err);
              }
            }
          };
          // 触发文件选择对话框
          fileInput.click();
        },
      });
    },

    // 获取html文本(字符串)
    getHTMLText() {
      let html = this.editor.getHtml();
      let css = this.editor.getCss();
      // js在编辑器中一般被解析在html中，也就是body标签内
      // let js = this.editor.getJs();
      return { html, css };
    },

    // 设置是否自动缓存
    setStore(option) {
      this.editor.StorageManager.getConfig().autoload = option;
    },

    // 判断是否有id对应页
    hasPage(id) {
      const result = this.pm.get(id);
      return result;
    },

    // 选择id对应页，也就是切换当前页
    selectPage(id) {
      this.pm.select(id);
    },

    // 删除id对应页
    removePage(id) {
      if (this.pm) {
        this.pm.remove(id);
      }
    },

    // 添加页
    addPage(id, name, data) {
      const newPage = {
        id: id,
        name: name,
        component: data || `<div>${name}</div><style>div{color:green}</style>`,
      };
      this.pm.add(newPage);
      // this.pm.select(this.pm.get(id));
    },

    // 添加预览事件
    toPreview() {
      try {
        let that = this;
        setTimeout(function () {
          that.editor.Commands.run("preview");
        }, 100);
      } catch (e) {
        console.log(e);
      }
      // document.getElementsByClassName('gjs-pn-btn fa fa-eye')[0].click();
    },

    // 停止预览
    toStopPreview() {
      this.editor.Commands.stop("preview");
    },

    // 全屏
    toFullscreen() {
      try {
        let that = this;
        setTimeout(function () {
          that.editor.Commands.run("fullscreen", { target: ".editorOutline" });
        }, 100);
      } catch (e) {
        console.log(e);
      }
      // document.getElementsByClassName('gjs-pn-btn fa fa-arrows-alt')[0].click();
    },

    // 退出全屏
    toStopFullscreen() {
      this.editor.Commands.stop("fullscreen", { target: ".editorOutline" });
    },

    // 全屏时应触发的事件
    fullscreen(editor) {
      // editor.on("command:run:before:fullscreen", () => {
      //   // 移除块的显示，转移到右侧
      //   editor.BlockManager.getConfig().appendTo = null;
      //   editor.Panels.addButton("views", {
      //     id: "open-blocks",
      //     className: "fa fa-th-large",
      //     command: "open-blocks",
      //     attributes: { title: "Open Blocks" },
      //   });
      // });
      // // 触发以下事件后，Panels按钮的blocks会消失
      // editor.on("command:stop:before:fullscreen", () => {
      //   // 删除Panels按钮后，需要选中其余的按钮
      //   editor.Panels.getButton("views","open-sm").set("active", true);
      //   // 调用后会删除Panels按钮
      //   editor.Panels.removeButton("views","open-blocks");
      //   // 调用后会渲染左侧的blocks，右侧的就会消失，原因是没有设置external属性为true
      //   this.createBlocks();
      // });
    },
    // 动态的构建blocks
    createBlocks() {
      this.editor.BlockManager.getConfig().appendTo = "#blocks";
      const blocks = this.editor.BlockManager.getAll();
      const newBlocksEl = this.editor.BlockManager.render(blocks.models, {
        external: true,
      });
      document.getElementById("blocks").appendChild(newBlocksEl);
    },

    // 预览时应触发的事件
    preview(editor) {
      let blocks = document.querySelector(".blocks");
      let gjs = document.querySelector(".gjs");
      editor.on("command:run:before:preview", () => {
        blocks.style.display = "none";
        gjs.classList.remove("el-col-21");
      });
      editor.on("command:stop:before:preview", () => {
        blocks.style.display = "block";
        gjs.classList.add("el-col-21");
      });
    },
  },
};
</script>

<style>
/* 设备字段 */
.gjs-devices-c .gjs-device-label {
  width: 50px;
}
.gjs-rte-action {
  width: 35px;
}
/* 左侧区块管理器整体样式 */
.blocks {
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  background: #575560;
  scrollbar-width: none;
  overflow-x: hidden;
}
/* 右侧面板样式 */
.gjs-pn-panel {
  background: #fff;
  scrollbar-width: none;
}
.gjs-pn-buttons {
  margin-right: 26px;
}
/* 预览编辑器内容的左上角的眼睛图标的样式 */
.gjs-off-prv {
  background: #575560;
}
/* 编辑器整体样式 */
.gjs-one-bg {
  background: #575560;
}
/* 编辑器按钮活动/选中的样式和区块管理器中组件悬浮样式 */
.gjs-four-color,
.gjs-block:hover {
  color: #75c4e8fc;
}
.gjs-block {
  transition: 0.5s;
}
.gjs-block:hover {
  height: auto;
}
.gjs-three-bg {
  background-color: #75c4e8fc;
  color: white;
}
/* 编辑器内文字及切换编辑器模式下拉栏(切换模拟不同端的编辑)的样式 */
.gjs-two-bg,
.gjs-select option {
  background: #575560;
}
/* 编辑器外一层的样式 */
.gjs {
  border-bottom-right-radius: 10px;
  border-top-right-radius: 10px;
  height: 100vh;
  overflow: hidden;
}
/* 编辑器内代码显示中的滚动条样式 */
.CodeMirror-vscrollbar {
  scrollbar-width: none;
}
/* 编辑器内代码显示中左侧序号一列的样式 */
.CodeMirror-scroll,
.CodeMirror-gutter {
  background-color: aliceblue;
  color: rgb(15, 22, 66);
}
/* 编辑器显示代码中HTML的字体颜色 */
.gjs-cm-editor#gjs-cm-htmlmixed #gjs-cm-title {
  color: #ddca7e;
}
/* 挂载编辑器样式 */
#gjs {
  height: 100vh;
  overflow-x: hidden;
  scrollbar-width: none;
}
/* .pages-wrp, .pages {
  display: flex;
  flex-direction: column
}
.pages-wrp {
  background: #333;
  padding: 5px;
}
.add-page {
  background: #444444;
  color: white;
  padding: 5px;
  border-radius: 2px;
  cursor: pointer;
  white-space: nowrap;
  margin-bottom: 10px;
}
.page {
  background-color: #444;
  color: white;
  padding: 5px;
  margin-bottom: 5px;
  border-radius: 2px;
  cursor: pointer;
}
.page .selected {
    background-color: #706f6f
  }

.page-close {
  opacity: 0.5;
  float: right;
  background-color: #2c2c2c;
  height: 20px;
  display: inline-block;
  width: 17px;
  text-align: center;
  border-radius: 3px;
}
.page-close :hover {
    opacity: 1;
  } */
</style>
